import React from 'react';
import util from 'util';
import {Button, Table, Modal, Form,message} from 'antd';
import {SearchDemo, RightButton, ColsEdit} from 'kpl';
import sys_dict from "sys_dict";

class A301 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tblSource: [],
            txt:"请输入内容",
            addForm:{"imageUrl":"123"},
            searchParams: {
                rolename: "",
                roletype: "",
                descript: "",
                "page": 1,
                "rows": sys_dict.defaultPageSize.toString()
            },
            totalCount: 0,
            isLoading: false,
            isupdate: false,
        }
        this.artical_id = "";
        this.iswailian = false;
    }

    componentDidMount() {
        let params = this.state.searchParams;
        this.refresh(params);
    }

    refresh(paramdic) {
        this.setState({isLoading: true}); 
        util.httpRequest({
            type: "POST", url: 'content030004.json', params: paramdic, plattype: '', success: function (result) {
                if (result.ret_code == "0000") {
                    this.setState({
                        tblSource: result.article_list,
                        totalCount: result.total
                    });
                }
            }.bind(this),
            complete: function () {
                this.setState({
                    isLoading: false
                })
            }.bind(this)
        });
    }

    search(params) {
        console.log(this);
        params.page = "1";
        params.rows = sys_dict.defaultPageSize.toString();
        this.setState({
            searchParams: params
        });
        this.refresh(params);
    }

    onShowSizeChange(current, pageSize) {
        console.log(current, pageSize);
        var params = this.state.searchParams;
        params.rows = pageSize;
        params.page = current;
        this.setState({searchParams: params});
        this.refresh(params);
    }

    onChange(page) {
        console.log(page);
        var params = this.state.searchParams;
        params.page = page;
        this.setState({searchParams: params});
        this.refresh(params);
    }

    getTableConfig(){
    	const pagination = {
            total: this.state.totalCount,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: sys_dict.pageSizeOptions,
            defaultPageSize: sys_dict.defaultPageSize,
            onShowSizeChange: this.onShowSizeChange.bind(this),
            onChange: this.onChange.bind(this)
        };
    	
        let tableConfig={};
    	tableConfig.queryConfig={
            searchTitle: "发布文章查询",
            searchInit: {
               
            },
            searchField: [
                [
                    {propsname: "文章标题：", propsKey: "title", propsType: "input", key: "1"},
                    {propsname: "发布人姓名：", propsKey: "release_user_name", propsType: "select", key: "2"},
                    {propsname: "开始时间：", propsKey: "release_begin_date", propsType: "datepicker", key: "3"},
                    {propsname: "截止时间：", propsKey: "release_end_date", propsType: "datepicker", key: "4"}
                ]
            ]
        };
    	
    	tableConfig.resultConfig={
    		     pagination: pagination,
                loading: this.state.isLoading,
                dataSource: this.state.tblSource,
                columns: [
	                {title: '标题',dataIndex: 'title',key: 'title'}, 
	                {title: '发布人',dataIndex: 'release_user_name',key: 'release_user_name'},
	                {title: '发布时间',dataIndex: 'release_datetime',key: 'release_datetime'},
	                {title: '是否置顶',dataIndex: 'if_top',key: 'if_top'},
	                {title: '操作',dataIndex: 'caozuo',
	                  render: (text, data, index) => (
                        <span>
                                <span className="ant-divider"></span>
                                <a onClick={this.row_updateRecord.bind(this, data, index)}>修改</a>
                                <span className="ant-divider"></span>
                                 <a onClick={this.row_deleteRecord.bind(this, data, index)}>删除</a>
                        </span>
                        )
	                }
                ]
            };

    	    return tableConfig;
    	}

    //文章详情查询
    row_updateRecord(record, type, e) {
        util.httpRequest({
            type: "POST",
            url: 'content030005.json',
            plattype: '',
            params: {article_id:record.article_id},
            success: function (result) {
                this.setState({
                    modalVisible : true,
                    isupdate : true,
                });
                var {setFieldsValue} = this.refs.addForm.getForm();
                setFieldsValue(result);
                this.artical_id = record.article_id;
            }.bind(this)
        });
    }

   row_deleteRecord(record, type, e) {
		var me = this;
        var sContent="若将文章:["+record.employee_name+"] 删除则用户将无法查看到此文章，确认删除吗？";
        var sOkText="确认删除";
        var sCancelText="不删除";
        
        Modal.confirm({
                title:sOkText,
                content: sContent,
                okText: sOkText,
                cancelText: sCancelText,
                onOk: function () {                  
                    util.httpRequest({
                        type: "POST",
                        url: 'content030006.json',
                        plattype: '',
                        params: record,
                        success: function (result) {
                            me.refresh(me.state.searchParams);
                        }.bind(this)
                    });
                }
            });

       var me = this;
       var sContent="若将文章:["+record.employee_name+"] 删除则用户将无法查看到此文章，确认删除吗？";
       var sOkText="确认删除";
       var sCancelText="不删除";

       Modal.confirm({
           title:sOkText,
           content: sContent,
           okText: sOkText,
           cancelText: sCancelText,
           onOk: function () {
               util.httpRequest({
                   type: "POST",
                   url: 'content030006.json',
                   plattype: '',
                   params: record,
                   success: function (result) {
                       me.refresh(me.state.searchParams);
                   }.bind(this)
               });
           }
       });

   }

      getAddFormConfig(){
    	const createConfig = {
            operateTitle: "新增外链文章",
            operateType: this.state.operateType,
            operateData: this.state.operateData,
            operateInit: {},
            operateColSm: 24,
            operateCol: {labelCol: 2, wrapperCol: 22},
            operateField: [
                 [
                    {
                        propsname: "文章标题：",
                        propsKey: "title",
                        propsType: "input",
                        key: "1",
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ],
                [
                    {
                        propsname: "文章类别：",
                        propsKey: "article_sort",
                        propsType: "acticltype",
                        visible:true,
                        key:"5",
                        rules: [{required: true, min: 0, message: '请选择'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ],
                [
                    {
                        propsname: "是否不置顶：",
                        propsKey: "if_top",
                        propsType: "radio",
                        visible:true,
                        key:"2",
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ],
                [
                    {
                        propsname: "是否外链：",
                        propsKey: "article_type",
                        propsType: "radio",
                        visible:true,
                        key:"2",
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ],
                [
                    {
                        propsname: "是否推送：",
                        propsKey: "if_push",
                        propsType: "radio",
                        visible:true,
                        key:"2",
                        rules: [{required: true, min: 0, message: '请选择'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ],
                [   {
                        propsname: "文章封面",
                        propsKey: "cover_img",
                        propsType: "image",
                        imageWidth:500,
                        imageHeight:150,
                        alt:"请点击上传图片",
                        imageUrl:this.state.addForm.imageUrl,
                        key:Math.random(),
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 6,
                        wrapperCol: 6
                    },
                    {
                        propsname: "上传",
                        propsKey: "cover_img_upload",
                        uploadCustomProps:{
                        	
                        	accept:"image/jpeg,image/png",
                        	showUploadList: this.state.open,
                            propsKey: "cover_img_upload",
				            name: 'file',
				            action: util.upUrl + 'platform/imgupload.json',
				            defaultFileList: [],
				            beforeUpload(file) {
				               return true;
				            },
				            onPreview: (file) => {
				                console.log("查看----->", file.url);
				                this.setState({
				                    previewImage: file.url,
				                    previewVisible: true,
				                });
				            },
				            onRemove: (file) => {
				                console.log("删除--->", file.url);
				            },
				            onChange: (info) => {

				                //console.log("---调用---");
				                if (info.file.status !== 'uploading') {
				                    console.log(info.file, info.fileList);
				                }
				                if (info.file.status === 'done') {
				                    this.setState({open: false});
									 if (info.file.response.file_name) {
				                        let obj = {};
				                        obj.pic_file_name = info.file.response.file_name;
				                        obj.pic_url_id = info.file.response.resource_id;
				                        let url = util.upUrl + "platform/showimg.json?resource_id=" + info.file.response.resource_id;
				                        console.log(this.state.addForm.imageUrl);
				                        addForm={imageUrl:url};
				                        this.state.addForm.imageUrl=url;
				                        let addForm={imageUrl:url};
				                        this.setState(addForm);
				                    }
				                    console.log(info, "上传完成", info.file.response.file_name, info.file.response.resource_id);
				                    message.info('上传图片成功!');
				                    this.open = false;
				                   
				
				                } else if (info.file.status === 'error') {
				                    message.info('上传图片失败!请重试！');
				                    console.log("error");
				                }
				            }
                        },
                        propsType: "imageupload",
                        key: "4",
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 6,
                        wrapperCol: 6
                    }
                ],
                [
                    {
                        propsname: "外链地址",
                        propsKey: "url",
                        propsType: "input",
                        txt:"请输入文字",
                        key: "3310",
                        rules: [{required: true, min: 0, message: '请输入'}],
                        labelCol: 12,
                        wrapperCol: 12
                    }
                ]
                //,
                //[
                //    {
                //        propsname: "文章内容",
                //        propsKey: "content",
                //        propsType: "editor",
                //        txt:"请输入文字",
                //        key: "3339",
                //        rules: [{required: true, min: 0, message: '请输入'}],
                //        labelCol: 12,
                //        wrapperCol: 12
                //    }
                //]
            ]
        };
        return createConfig;
   }
    
    handleCancel() {
        this.setState({
            modalVisible: false,
            modalDetailVisible: false
        });
        this.state.addForm.imageUrl="";
    }   
    add_display() {
        this.iswailian = true;
        this.setState({
            modalVisible: true,
            operateType: "ADD",
            operateData: {},
            modalTitle: "新增",
            isupdate : false,
        }, function () {
            var form = this.refs.addForm.getForm();
            form.resetFields();
        });
    }

    add_display1(){
        this.iswailian = false;
        this.setState({
            modalVisible: true,
            operateType: "ADD",
            operateData: {},
            modalTitle: "新增",
            isupdate : false,
        }, function () {
            var form = this.refs.addForm.getForm();
            form.resetFields();
        });
    }

    add_save(values) {

        var form = this.refs.addForm.getForm();
        var refss= this.refs;

        if(this.state.isupdate){
            form.validateFields((errors, values) => {
                console.log("values");
                console.log(values);
                //关闭窗口
                console.log("form");
                console.log(form);
                console.log("values.cover_img_upload");
                console.log(values.cover_img_upload);
                if (values.cover_img_upload != undefined && values.cover_img_upload != "") {
                    var obj = {};
                    obj.article_id = this.artical_id;
                    obj.cover_file_name = values.cover_img_upload.file.response.file_name;
                    obj.cover_resource_id = values.cover_img_upload.file.response.resource_id;
                    obj.content_resource_id = values.cover_img_upload.file.response.resource_id;
                    obj.content_file_name = values.cover_img_upload.file.response.file_name;
                    obj.if_push = values.if_push;
                    obj.if_top = values.if_top;
                    obj.title = values.title;
                    if(values.article_type=="0") {
                        obj.content = this.state.txt;
                    }else {
                        obj.url = values.url;
                    }
                    obj.article_type = values.article_type;
                    obj.article_sort = values.article_sort;
                    console.log(this.state.txt);

                } else{
                    message.error("请先选择文件上传");
                    this.handleCancel();
                    return;
                }

                util.httpRequest({
                    type: "POST",
                    url: 'content030002.json',
                    plattype: '',
                    params: obj,
                    success: function (result) {
                        if(result.ret_code=="0000"){
                            message.success("处理成功");
                            this.handleCancel();
                            this.componentDidMount();
                        }else{
                            message.error("处理失败");
                            this.handleCancel();
                            this.componentDidMount();
                        }
                    }.bind(this)
                });
            });
        }else {
            form.validateFields((errors, values) => {
                console.log("values");
                console.log(values);
                //关闭窗口
                console.log("form");
                console.log(form);
                console.log("values.cover_img_upload");
                console.log(values.cover_img_upload);
                if (values.cover_img_upload != undefined && values.cover_img_upload != "") {
                    var obj = {};
                    obj.cover_file_name = values.cover_img_upload.file.response.file_name;
                    obj.cover_resource_id = values.cover_img_upload.file.response.resource_id;
                    obj.content_resource_id = values.cover_img_upload.file.response.resource_id;
                    obj.content_file_name = values.cover_img_upload.file.response.file_name;
                    obj.if_top = values.if_top;
                    obj.if_push = values.if_push;
                    obj.title = values.title;
                    if(values.article_type=="0") {
                        obj.content = this.state.txt;
                    }else {
                        obj.url = values.url;
                    }
                    obj.article_type = values.article_type;
                    obj.article_sort = values.article_sort;
                    console.log(this.state.txt);
                } else{
                    message.error("请先选择文件上传");
                    this.handleCancel();
                    return;
                }

                util.httpRequest({
                    type: "POST",
                    url: 'content030001.json',
                    plattype: '',
                    params: obj,
                    success: function (result) {
                        if(result.ret_code=="0000"){
                            message.success("处理成功");
                            this.handleCancel();
                            this.componentDidMount();
                        }else{
                            message.error("处理失败");
                            this.handleCancel();
                            this.componentDidMount();
                        }
                    }.bind(this)
                });
            });
        }


    }

    editorChange(editortxt) {
        console.log("pro:", editortxt);
        this.state.txt = editortxt;
    }

    render() {

        let tableConfig = this.getTableConfig();
        let addFormConfig = this.getAddFormConfig();
        return (
            <div>
                <SearchDemo search={this.search.bind(this)} searchConfig={tableConfig.queryConfig}></SearchDemo>
                <RightButton styleName="addBtn" propsKey="121" btnTxt="+新增外链文章" oprate={this.add_display.bind(this)}> </RightButton>
                <RightButton styleName="addBtn1" propsKey="122" btnTxt="+新增内部文章" oprate={this.add_display1.bind(this)}> </RightButton>
                <Table {...tableConfig.resultConfig}></Table>
                <Modal visible={this.state.modalVisible} title={addFormConfig.operateTitle} width="60%"
                               closable={false} footer={[
                     <Button key="back" type="ghost" size="large"
                                    onClick={this.handleCancel.bind(this)}>取消</Button>,
                     <Button key="submit" type="primary" size="large"
                                    onClick={this.add_save.bind(this)}>{this.state.isupdate?"确定修改":"确定上传"}</Button>
                ]}>
                <ColsEdit editorChange={this.editorChange.bind(this)} setTxt={this.state.txt} key={Math.random()} ref="addForm" key="fsjfds"  config={addFormConfig}></ColsEdit>
                </Modal>
            </div>
        );
    }
}

export default A301;